package com.cn.shuangzi.userinfo.common;

import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.bean.ActivelyPaymentInfo;
import com.cn.shuangzi.bean.VipInfo;
import com.cn.shuangzi.common.SZCommonEvent;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.loginplugin.bean.SZUserInfo;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.cn.shuangzi.view.sweet_alert.SweetAlertDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.List;

public class UserManager {

    public static String PLATFORM_PHONE = "PHONE";
    public static String PLATFORM_WECHAT = "WECHAT";
    public static String PLATFORM_WECHAT_2 = "WECHAT_2";
    public static String PLATFORM_ALIPAY = "ALIPAY";

    private static UserManager INSTANCE;
    private SZUserInfo userInfo;
    private VipInfo vipInfo;
    private boolean isShownDueAlert;
    private static String userInfoKey = SZConst.USER_INFO_SZ;

    public static void setUserInfoKey(String userInfoKey){
        UserManager.userInfoKey = userInfoKey;
    }
    private UserManager() {
        isShownDueAlert = false;
    }

    public static UserManager getInstance() {
        if (INSTANCE == null) {
            synchronized (UserManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new UserManager();
                }
            }
        }
        return INSTANCE;
    }

    public void showVipDueAlert(SZBaseActivity activity, Class<?> buyVipClass) {
        showVipDueAlert(true,activity, buyVipClass);
    }

    public void showVipDueAlert(boolean isJudgeContinuousSubscription,SZBaseActivity activity, Class<?> buyVipClass) {
        showVipDueAlert(isJudgeContinuousSubscription,activity, buyVipClass, 7, "会员即将到期"
                , "您的会员即将在" + SZDateUtil.getShowYearMonthDate(new Date(getVipInfo().getMemberValidityTime())) + "到期，为了不影响您使用会员权限，请尽快续费"
                , "续费会员", "稍后再说");
    }

    public void showVipDueAlert(boolean isJudgeContinuousSubscription,SZBaseActivity activity, Class<?> buyVipClass, int distanceShow) {
        showVipDueAlert(isJudgeContinuousSubscription,activity, buyVipClass, distanceShow, "会员即将到期"
                , "您的会员即将在" + SZDateUtil.getShowYearMonthDate(new Date(getVipInfo().getMemberValidityTime())) + "到期，为了不影响您使用会员权限，请尽快续费"
                , "续费会员", "稍后再说");
    }

    public void showVipDueAlert(boolean isJudgeContinuousSubscription , final SZBaseActivity activity, final Class<?> buyVipClass, int distanceShow
            , final String title, final String content, final String okText, final String cancelText) {
        if (isShownDueAlert) {
            return;
        }
        if (getVipInfo() == null) {
            return;
        }
        long time = getVipInfo().getMemberValidityTime();
        int distance = SZDateUtil.getDayDistance(new Date(), new Date(time));
        if (distance > 0 && distance <= distanceShow) {
            if(isJudgeContinuousSubscription){
                SZRetrofitManager.getInstance().request(SZRetrofitManager.getInstance().getSZRequest().getActivelyPaymentAgreement(getUserInfo().getId()), null, new SZCommonResponseListener(false) {
                    @Override
                    public void onResponseSuccess(String data) {
                        List<ActivelyPaymentInfo> activelyPaymentInfoList = new Gson().fromJson(data,new TypeToken<List<ActivelyPaymentInfo>>(){}.getType());
                        if(!SZValidatorUtil.isValidList(activelyPaymentInfoList)) {
                            showDueAlert(activity, buyVipClass, title, content, okText, cancelText);
                        }
                    }

                    @Override
                    public void onResponseError(int i, String s) {
                    }
                });
            }else{
                showDueAlert(activity,buyVipClass,title,content,okText,cancelText);
            }

        }
    }
    private void showDueAlert(final SZBaseActivity activity, final Class<?> buyVipClass, String title, String content, String okText, String cancelText){
        isShownDueAlert = true;
        activity.showAlert(SweetAlertDialog.WARNING_TYPE, title, content
                , okText, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                        activity.startActivity(buyVipClass);
                    }
                }, cancelText, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismissWithAnimation();
                    }
                }, true);
    }
    public void clearUser() {
        setVipInfo(null);
        setUserInfo(null);
    }

    public boolean isVip() {
        VipInfo vipInfo = getVipInfo();
        if (vipInfo != null) {
            boolean isValidTime = vipInfo.getMemberValidityTime() >= System.currentTimeMillis();
            if (!isValidTime) {
                setVipInfo(null);
            }
            return isValidTime;
        }
        return false;
    }

    public void setVipInfo(VipInfo vipInfo) {
        if (getUserInfo() != null) {
            this.vipInfo = vipInfo;
            setVipInfo(getUserInfo().getId(), vipInfo);
        }
    }

    public VipInfo getVipInfo() {
        if (getUserInfo() == null) {
            return null;
        }
        if (vipInfo == null) {
            if (getUserInfo() != null) {
                vipInfo = getVipInfo(getUserInfo().getId());
            }
        }
        return vipInfo;
    }

    private VipInfo getVipInfo(String userId) {
        try {
            if (SZValidatorUtil.isValidString(userId)) {
                String vip = new SZXmlUtil(SZConst.VIP_INFO).getString(userId);
                if (SZValidatorUtil.isValidString(vip)) {
                    return new Gson().fromJson(vip, VipInfo.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setVipInfo(String userId, VipInfo vipInfo) {
        if (SZValidatorUtil.isValidString(userId)) {
            if (vipInfo != null) {
                new SZXmlUtil(SZConst.VIP_INFO).put(userId, new Gson().toJson(vipInfo));
            } else {
                new SZXmlUtil(SZConst.VIP_INFO).remove(userId);
            }
        }
    }

    public String getToken() {
        if (getUserInfo() != null) {
            return getUserInfo().getToken();
        }
        return null;
    }

    public String getPhone() {
        if (getUserInfo() != null) {
            return getUserInfo().getPhone();
        }
        return null;
    }

    public String getAvatar() {
        if (getUserInfo() != null) {
            return getUserInfo().getAvatar();
        }
        return null;
    }

    public String getNickname() {
        if (getUserInfo() != null) {
            return getUserInfo().getNickname();
        }
        return null;
    }

    public String getId() {
        if (getUserInfo() != null) {
            return getUserInfo().getId();
        }
        return null;
    }

    public void setNickname(String nickname) {
        if (getUserInfo() != null) {
            getUserInfo().setNickname(nickname);
            setUserInfo(getUserInfo());
        }
    }

    public void setAvatar(String avatar) {
        if (getUserInfo() != null) {
            getUserInfo().setAvatar(avatar);
            setUserInfo(getUserInfo());
        }
    }

    public void setPhone(String phone) {
        if (getUserInfo() != null) {
            getUserInfo().setPhone(phone);
            setUserInfo(getUserInfo());
        }
    }


    public SZUserInfo getUserInfo() {
        try {
            if (userInfo == null) {
                String user = new SZXmlUtil(userInfoKey).getString(userInfoKey);
                if (SZValidatorUtil.isValidString(user)) {
                    userInfo = new Gson().fromJson(user, SZUserInfo.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            setUserInfo(null);
            EventBus.getDefault().post(new SZCommonEvent(SZCommonEvent.LOGOUT_EVENT));
        }
        return userInfo;
    }

    public void setUserInfo(SZUserInfo userInfo) {
        SZXmlUtil xmlUtil = new SZXmlUtil(userInfoKey);
        if (userInfo == null) {
            xmlUtil.clear();
        } else {
            xmlUtil.put(userInfoKey, new Gson().toJson(userInfo));
        }
        this.userInfo = userInfo;
    }

    public void onDestroy() {
        isShownDueAlert = false;
    }
}
